import { Component } from '@angular/core';
import { NavController, IonicPage, NavParams, ToastController } from 'ionic-angular';
import { Socket } from 'ng-socket-io';
import { Observable,Subscription } from 'rxjs';
import { LoginPage } from '../login/login';
 
@IonicPage({
  name:'ChatRoomPage'
})
@Component({
  selector: 'page-chat-room',
  templateUrl: 'chat-room.html',
})
export class ChatRoomPage {
  messages = [];
  nickname = '';
  message = '';
  
  user:any;

  Toer:any;//reciver;

  listen:Subscription;

  listen2:Subscription;

  constructor(private navCtrl: NavController, private navParams: NavParams, private socket: Socket, private toastCtrl: ToastController) {

    let _user = localStorage.getItem('user');

    this.Toer = this.navParams.get('nickname');
    
    if (_user) {
      this.user = JSON.parse(_user);
      this.nickname = this.user.username;

      this.socket.emit('init', this.user);
      this.socket.emit('set-nickname', this.Toer.username);
      
    }else{
      this.navCtrl.push(LoginPage);
    }

    
    
    // this.socket.connect();
    this.listen = this.getMessages().subscribe(message => {

      console.log(this.messages);
      setTimeout(()=>{
        this.messages.push(message);
      },100);
      
    }); 
   
  }
 
  sendMessage() {
    
    this.socket.emit('private-message', { from:this.user,to:this.Toer,msg: this.message });


    this.messages.push({from :this.nickname,msg:this.message,created:new Date()});

    this.message = '';
  }
 
  getMessages() {
    let observable = new Observable(observer => {
      this.socket.on('private-message', (data) => {
        observer.next(data);
      });
    })
    return observable;
  }
 
  
 
  ionViewWillLeave() {
    // this.socket.disconnect();

    if(this.listen){
      this.listen.unsubscribe();
    }

    if(this.listen2){
      this.listen2.unsubscribe();
    }
  }
 
  showToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }
}
